package com.helu.lubike.utils;

import com.helu.lubike.BuildConfig;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by helu on 17-2-12.
 */
public class HTTPHelper {
    /**
     * 这一部分配置常量，可以抽取出常量类
     */
    private static final String BASE_PATH = "http://api.soongkun.xyz/lubike/";//访问的地址
    private static final long DEFAULT_TIMEOUT = 5000;//默认超时时间(毫秒)
    private static HTTPHelper instance = null;

    private Retrofit mRetrofit;

    private HTTPHelper() {
        OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();

        LoggingInterceptor loggingInterceptor = new LoggingInterceptor();
        loggingInterceptor.setLevel(BuildConfig.DEBUG ? LoggingInterceptor.Level.BODY : LoggingInterceptor.Level.BASIC);
        okHttpClient.addInterceptor(loggingInterceptor);

        okHttpClient.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
        mRetrofit = new Retrofit.Builder()
                .client(okHttpClient.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(BASE_PATH)
                .build();
    }

    /**
     * 获取单例对象
     *
     * @return
     */
    public static HTTPHelper getInstance() {
        if (instance == null) {
            return new HTTPHelper();
        } else {
            return instance;
        }
    }

    public <T> T create(Class<T> clazz) {
        return mRetrofit.create(clazz);
    }
}
